const moment = require('moment')
const async = require('async')
const request = require('request')
const Order = require('../../model/Order')
const xmlParse = require('xml2js').parseString
const MemberCard = require('../../model/MemberCard')
const UserPoint = require('../../model/userPoint')
const Member = require('../../model/Member')
const MyVoucher = require('../../model/MyVoucher')
const wxPublicAccessToken = require('../../util/businessUtil/wxPublicAccessToken')


module.exports = {
    notify: async (req, res, next) => {
        try {
            var data = ''
            req.on('data', function (chuck) {
                console.log(chuck, 'cc')
                data += chuck
            })
            req.on('end', () => {
                xmlParse(data, (err, result) => {
                    var result_code = result['xml'].result_code[0]
                    var return_code = result['xml'].return_code[0]
                    console.log(result_code, return_code, 'bbbbbbb')
                    if ((result_code == 'SUCCESS') && (return_code == 'SUCCESS')) {
                        var id = result['xml'].out_trade_no[0]
                        const transaction_id = result['xml'].transaction_id[0]
                        const price = parseInt(result['xml'].total_fee[0]) / 100
                        console.log(id, transaction_id, price,)
                        processPaymentOrder(id, transaction_id,req,res)

                        // async.parallel([
                        //     // event / place
                        //     function (callback) {
                        //         Order.findOneAndUpdate({ _id: id }, { wxPayID: transaction_id, status: 1 }).exec(function (err, data) {
                        //             if (data.usePoint == 1) {
                        //                 let newPointHistory = new PointHistory({
                        //                     openid: data.openid,
                        //                     unionID: data.unionID,
                        //                     order: data._id,
                        //                     expenseDate: new Date(),
                        //                     manual: 0, // 1位人工，0为自动
                        //                     amount: data.amountOfUsePoint, // 变动的积分数量
                        //                     type: 1, // 0 为加，1为减
                        //                     isDelete: 0,
                        //                 })
                        //                 newPointHistory.save(function (err, PointHistoryData) {
                        //                     MemberCard.findOne({ isDelete: 0 }).exec(function (err, memberCard) {
                        //                         Member.findOne({ openid: data.openid, isDelete: 0 }).exec(function (err, member) {
                        //                             member.point = member.point - data.amountOfUsePoint
                        //                             member.updatedAt = new Date()
                        //                             member.save(function (err, newMember) {
                        //                                 UserPoint.findOne({ openid: data.openid, isDelete: 0 }).exec(function (err, userPoint) {
                        //                                     userPoint.current = userPoint.current - data.amountOfUsePoint
                        //                                     userPoint.updatedAt = new Date()
                        //                                     userPoint.save(function (err, newUserPoint) {
                        //                                         wxPublicAccessToken.getAccessToken(function (token) {
                        //                                             request({
                        //                                                 url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                        //                                                 method: "POST",
                        //                                                 timeout: 10000,
                        //                                                 encoding: null,
                        //                                                 json: {
                        //                                                     "code": newMember.code,
                        //                                                     "card_id": memberCard.cardId,
                        //                                                     "bonus": newMember.point
                        //                                                 }
                        //                                             }, function (error, response, body) {
                        //                                                 console.log(error)
                        //                                                 res.send({ 'code': 200 })
                        //                                             })
                        //                                         })
                        //                                     })
                        //                                 })
                        //                             })
                        //                         })
                        //                     })
                        //                 })
                        //             }
                        //             callback(null, '')
                        //         })

                        //     }

                        // ], function (err) {
                        //     res.send({ 'code': 200 })
                        // })


                        // async () =>{
                        //     let order = await Order.findOneAndUpdate({ _id: id }, { wxPayID: transaction_id, status: 1 }).exec()
                        //     if(order.usePoint == 1){
                        //         let newPointHistory = new PointHistory({
                        //             openid: order.openid,
                        //             unionID: order.unionID,
                        //             order: order._id,
                        //             expenseDate: new Date(),
                        //             manual: 0, // 1位人工，0为自动
                        //             amount: order.amountOfUsePoint, // 变动的积分数量
                        //             type: 1, // 0 为加，1为减
                        //             isDelete: 0,
                        //         })
                        //         await newPointHistory.save()
                        //         let memberCardNumber = (await MemberCard.findOne({isDelete:0}).exec()).cardId
                        //         let member = await Member.findOne({ openid: order.openid, isDelete: 0 }).exec()
                        //         let userPoint = await UserPoint.findOne({ openid: order.openid, isDelete: 0 }).exec()
                        //         member.point = member.point - order.amountOfUsePoint
                        //         member.updatedAt = new Date()
                        //         await member.save()
                        //         userPoint.current = userPoint.current - order.amountOfUsePoint
                        //         userPoint.updatedAt = new Date()
                        //         await userPoint.save()
                        // wxPublicAccessToken.getAccessToken(function(token) {
                        //     request({
                        //              url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                        //              method: "POST",
                        //              timeout: 10000,
                        //              encoding: null,
                        //              json:{
                        //                 "code": member.code,
                        //                 "card_id": memberCardNumber,
                        //                 "bonus": member.point
                        //              }
                        //          },function(error, response, body){
                        //             console.log(error)
                        //             res.send({ 'code': 200 })
                        //     })
                        // })
                        //     }else{
                        //         res.send({ 'code': 200 }) 
                        //     }
                        // }
                    }
                    else {
                        res.send({ 'code': 200 })
                    }
                })
            })
        } catch (e) {
            next(e)
        }
    },
};

async function processPaymentOrder(id,transaction_id,req,res) {
    // let order = await Order.findOneAndUpdate({ _id: id }, { wxPayID: transaction_id, status: 1, updatedAt: new Date(), paidAt: new Date() }).exec()
    let order = await Order.findOne({_id: id}).exec()
    order.wxPayID = transaction_id
    order.status = 1
    order.updatedAt = new Date()
    order.paidAt =  new Date()
    await order.save()
    if (order.type == 0) {
        if (order.usePoint == 1) {
            let newPointHistory = new PointHistory({
                openid: order.openid,
                unionID: order.unionID,
                order: order._id,
                expenseDate: new Date(),
                manual: 0, // 1位人工，0为自动
                amount: order.amountOfUsePoint, // 变动的积分数量
                type: 1, // 0 为加，1为减
                isDelete: 0,
            })
            await newPointHistory.save()
            let memberCardNumber = (await MemberCard.findOne({ isDelete: 0 }).exec()).cardId
            let member = await Member.findOne({ openid: order.openid, isDelete: 0 }).exec()
            let userPoint = await UserPoint.findOne({ openid: order.openid, isDelete: 0 }).exec()
            member.point = member.point - order.amountOfUsePoint
            member.updatedAt = new Date()
            await member.save()
            userPoint.current = userPoint.current - order.amountOfUsePoint
            userPoint.updatedAt = new Date()
            await userPoint.save()
            wxPublicAccessToken.getAccessToken(function (token) {
                request({
                    url: 'https://api.weixin.qq.com/card/membercard/updateuser?access_token=' + token,
                    method: "POST",
                    timeout: 10000,
                    encoding: null,
                    json: {
                        "code": member.code,
                        "card_id": memberCardNumber,
                        "bonus": member.point
                    }
                }, function (error, response, body) {
                    console.log(error)
                    res.send({ 'code': 200 })
                })
            })
        }
    } else if (order.type == 1) {
        // order.updatedAt = new Date()
        // order.paidAt = new Date()
        // await order.save()
        for (let i = 0; i <parseInt(order.products[0].amount); i++) {
            let newMyVoucher = new MyVoucher({
                openid: order.openid,
                unionID: order.unionID,
                voucher: order.products[0].voucher,
                amount: 1,
                status: 0,//0未使用，1使用
                updatedAt: new Date(),
                order:order._id,
                isDelete:0
            })
            await newMyVoucher.save()
        }
        res.send({ 'code': 200 })
    }
}